import WebHeader from '@/www/components/WebHeader'
import WebFooter from '@/www/components/WebFooter'
import { getQuote, uploadFile, postQuoteOrder } from '@/apiv2/quote'
import yun from '@/utils/yun'
import categoryFilter from 'echarts/src/chart/graph/categoryFilter'
import { indexOf } from 'codemirror/src/util/misc'

const CODE = 'Album'

export default {
  components: { WebHeader, WebFooter },
  data() {
    return {
      quoteData: undefined,
      laminationDisable: undefined,
      checkValue: {
        flagLamination: false,//覆膜
      },

      nullListObjectType:{
        insidePage: {category:undefined,quantity:undefined},
      },

      quoteValue: {
        category: undefined,
        insideCategory1: undefined,
        insideCategory2: undefined,
        insidePageQuantity1: 16,
        insidePageQuantity2: 0,
        customQuantity: 1,
        style: 1,
        quantity: undefined,
        size: undefined,
        customLength: undefined,
        customWidth: undefined,
        lamination: 'matteFilm',
        laminationSide: '1',
        insidePageList:[
          {
            category: undefined,
            quantity: undefined
          }
        ]
      },

      processSelectOptions: {

      },

      customSize:false,
      user: undefined,
      quote: undefined,
      quoteList: undefined,
      detail: undefined,
      fileList: [],
      postData: {
        quantity: undefined,
        detail: undefined,
        amount: undefined,
        fileIds: undefined
      },
      note: undefined
    }
  },

  created(){
    const user = JSON.parse(localStorage.getItem('user'))
    this.user = user

    getQuote(CODE).then(res => {
      let quoteData = res.config
      this.quoteValue.category = quoteData.cateData.list[0].name
      this.quoteValue.insideCategory1 = quoteData.cateData.list[0].name
      this.quoteValue.insideCategory2 = quoteData.cateData.list[0].name
      this.quoteValue.size = quoteData.sizeData.list[0].name
      this.quoteData = quoteData
    })
  },

  methods: {

    onCategoryChange(){
      this.quoteData.cateData.list.forEach(item => {
        if(item.name == this.quoteValue.category){
          this.laminationDisable = item.canLamination
          if(!item.canLamination){
            this.checkValue.flagLamination = false
          }
          this.gramList = item.gramList
          this.quoteValue.gram = item.gramList[0].gram
        }
      })
    },

    getA3Price(category,color,gram,rate){
      let cateList = this.quoteData.cateData.list
      let price = 0
      cateList.forEach(item => {
        if(item.name == category){
          item.gramList.forEach(sitem => {
            if(parseInt(gram) == parseInt(sitem.gram)){
              price = parseFloat(item[color + 'Price']) * parseFloat(rate) + parseFloat(sitem.price)
            }
          })
          return price
        }
      })
      return price
    },



    getQuote(){
      let detail = ''

      let {customSize,quoteData,quoteValue,checkValue,postData} = this

      const FINAL_QUANTITY = this.quoteValue.quantity ? parseInt(this.quoteValue.quantity) : parseInt(this.quoteValue.customQuantity)//客户下单数量
      const PVALUE_OF_PER_UNIT = 4 + parseInt(quoteValue.insidePageQuantity1) + parseInt(quoteValue.insidePageQuantity2)//单本P数

      let sizeItem = undefined
      for(let i = 0; i < quoteData.sizeData.list.length; i++){
        if(quoteValue.size == quoteData.sizeData.list[i].name){
          sizeItem = quoteData.sizeData.list[i]
          break
        }
      }

      console.log('单本P数：' + PVALUE_OF_PER_UNIT)
      console.log('成品尺寸：' + sizeItem.size)
      console.log('拼版尺寸：' + sizeItem.typesetSize)
      console.log(yun.SINGLE_PAGE_SIZE[sizeItem.size])

      return

      //总用纸信息
      let pageArr = [
        {
          category: quoteValue.category,
          size: SIZE_OF_PER_PAGE,
          quantity: FINAL_QUANTITY,
          repeatCount: 1
        }
      ]

      if(parseInt(quoteValue.insidePageQuantity1) >= 4){
        pageArr.push({
          category: quoteValue.insideCategory1,
          size: SIZE_OF_PER_PAGE,
          quantity: FINAL_QUANTITY,
          repeatCount: parseInt(parseInt(quoteValue.insidePageQuantity1) / 4)
        })
      }

      if(parseInt(quoteValue.insidePageQuantity2) >= 4){
        pageArr.push({
          category: quoteValue.insideCategory2,
          size: SIZE_OF_PER_PAGE,
          quantity: FINAL_QUANTITY,
          repeatCount: parseInt(parseInt(quoteValue.insidePageQuantity2) / 4)
        })
      }

      let materialAmount = parseFloat(this.getAllStuffAmount(pageArr))

      console.log('----------'+materialAmount)


      let processAmount = 0

      let totalAmount = parseFloat(materialAmount + processAmount).toFixed(2)

      totalAmount = totalAmount < parseFloat(quoteData.param.minimumPrice) ? parseFloat(quoteData.param.minimumPrice) : totalAmount

      let quoteList = [{
        materialAmount: materialAmount.toFixed(2),
        quantity: FINAL_QUANTITY,
        processAmount: processAmount.toFixed(2),
        totalAmount: totalAmount
      }]

      let defaultFlag = false
      postData.amount = totalAmount
      postData.detail = detail
      this.postData = postData
      this.quoteList = quoteList
    },

    getAllStuffAmount(arr){
      console.log('getAllStuffAmount-arr')
      console.log(arr)
      const {quoteValue,quoteData} = this
      let amount = 0
      for(let i = 0; i < arr.length; i++){
        let info = arr[i]
        amount += parseFloat(this.caculatePageAmount(info)) * parseFloat(info.repeatCount)
        console.log('pageprice============================================================')
        console.log(parseFloat(this.caculatePageAmount(info)))
      }
      return amount.toFixed(2)
    },

    caculatePageAmount(page){
      console.log('待计算page---:')
      console.log(page)
      let {quoteValue,quoteData} = this
      let basePage = this.getPageFromSize(page.size)//拼版纸张
      console.log('拼版basePage---:')
      console.log(basePage)
      let makeUpCountPerPage = yun.getCountMakeupInSize(page.size,basePage.size)//单纸拼版数量
      console.log('单张拼版数量makeUpCountPerPage---:')
      console.log(makeUpCountPerPage)
      let finalPageCount = Math.round(parseFloat(page.quantity) / parseFloat(makeUpCountPerPage))//最终用纸数量
      console.log('最终需要纸张finalPageCount---:')
      console.log(finalPageCount)
      let quantityList = []//材料数量组合
      let cateA5PriceList = []
      for(let i = 0; i < quoteData.cateData.list.length; i++){
        let cateInfo = quoteData.cateData.list[i]
        if(page.category == cateInfo.name){
          for(let j = 0; j < cateInfo.quantityA5PriceList.length; j++){
            quantityList.push(parseInt(cateInfo.quantityA5PriceList[j].quantity))
            cateA5PriceList.push(cateInfo.quantityA5PriceList[j])
          }
        }
      }
      // console.log('数量列表quantityList---:')
      // console.log(quantityList)
      // console.log('cateA5PriceList---:')
      // console.log(cateA5PriceList)
      let quantitySet = this.getQuantitySet(quantityList,finalPageCount)
      let amount = 0

      console.log('数量组合quantitySet---:')
      console.log(quantitySet)
console.log('---------------------------------------------------------------------------------------------------------')
      for(let i = 0; i < quantitySet.length; i++){
        let qsItem = quantitySet[i]
        for(let j = 0; j < cateA5PriceList.length; j++){
          let cpItem = cateA5PriceList[j]
          if(qsItem.quantity == parseInt(cpItem.quantity)){
            amount = amount + parseFloat(cpItem.price) * parseFloat(qsItem.count) * parseFloat(basePage.a5ratios)
          }
        }
      }
console.log('---------------------------------------------------------------------------------------------------------')
      console.log('+++++++++-------------------------------------------' + amount)
      return amount
    },

    //获取数量组合
    getQuantitySet(arr,quantity){
      console.log('计算数量组合+++' + quantity)
      if(indexOf(arr,quantity) > -1){
        return [{quantity:quantity,count:1}]
      }else{
        let setList = []
        let targetQuantity = quantity
        for(let i = arr.length - 1; i > -1; i--){
          let step = arr[i]
          if(targetQuantity > step){
            if((i == 0)){
              setList.push({quantity:arr[1],count:1})
              break
            }
            let count = parseInt(targetQuantity / step)
            setList.push({quantity:step,count:count})
            targetQuantity = targetQuantity - step * count
            if(targetQuantity == 0){
              break
            }
          }else if(targetQuantity == step){
            setList.push({quantity:step,count:parseInt(targetQuantity / step)})
            break
          }else{
            if((i == 0)){
              setList.push({quantity:step,count:1})
            }
          }
        }
        return setList
      }
    },

    getPageFromSize(size){
      // console.log('yun.PAGE_SIZE.list---:')
      for(let i = 0; i < yun.PAGE_SIZE.length; i++){
        let pageSize = yun.PAGE_SIZE[i]
        // console.log(pageSize.size)
        if(!yun.ifPageAreaBiggerThan(size,pageSize.size)){
          return pageSize
        }
      }
      return null
    },

    //范围取值
    getQuantityRangeValue(list,quantity){
      let price = parseFloat(list[list.length - 1].price)
      for(let i=0;i<list.length;i++){
        let item = list[i]
        if(quantity >= parseInt(item.start) && quantity <= parseInt(item.end)){
          price = parseFloat(item.price)
          break
        }
      }
      return price
    },


    //自定义尺寸切换
    onCustomSizeToggle(){
      this.quoteValue.customLength = undefined
      this.quoteValue.customWidth = undefined
    },

    selectQuantity(){
      if(this.quoteValue.quantity){
        this.quoteValue.customQuantity = undefined
      }
    },
    customQuantity(){
      if(this.quoteValue.customQuantity){
        this.quoteValue.quantity = undefined
      }else{
        this.quoteValue.quantity = this.quoteData.stepData.list[0]
      }
    },

    syncCheck(name,target){
      if(this.checkValue[name]){
        this.checkValue[target] = true
      }
    },

    offCheck(name,target){
      if(!this.checkValue[name]){
        this.checkValue[target] = false
      }
    },

    submitOrder(){
      const {fileList,postData} = this

      if(fileList.length < 1){
        this.$message.error('请上传设计稿')
        return
      }

      let fileIds = [];
      fileList.forEach(item => {
        fileIds.push(item.id)
      })
      postData.fileIds = fileIds

      const loading = this.$loading({
        lock: true,
        text: '正在创建订单',
        spinner: 'el-icon-loading',
        background: 'rgba(0,0,0,0.7)'
      });

      postQuoteOrder(postData).then(res => {
        loading.close()
        this.$message.success('成功创建订单')
        this.$router.push({
          path: '/submitOrder',
          query: { id : res.id}
        })
      }).catch(err => {
        loading.close()
        this.$message.error('创建订单失败')
      })
    },

    handleUpload: async function(data){
      const formData = new FormData()
      formData.append('file', data.file)
      const res = await uploadFile(formData)
      let fileList = this.fileList
      fileList.push(res.file)
      this.fileList = fileList
      console.log(fileList)
    },

    //获取最终尺寸
    getFinalSize(){
      let {quoteValue,customSize} = this
      let length = undefined
      let width = undefined
      if(quoteValue.customLength && quoteValue.customWidth && customSize){
        length = parseInt(quoteValue.customLength)
        width = parseInt(quoteValue.customWidth)
      }else if(quoteValue.size){
        let sizeStr = quoteValue.size.match(/\d+\*\d+/)[0]
        length = parseInt(sizeStr.split('*')[0])
        width = parseInt(sizeStr.split('*')[1])
      }
      return {
        length: length,
        width: width
      }
    },

  }
}
